#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import time
import sched
import Pyconfig
import requests
import DB
import json
import datetime
import service.MainService
import sys
import request
import httplib2


# 调用微服务测试心跳
def ms_version(msname):
    try:
        url = Pyconfig.yn_url + "/" + msname
        req = requests.get(url)
        print(json.loads(req.text))
        s = sched.scheduler(time.time, time.sleep)
        if (json.loads(req.text)['succ'] == True):
            print(msname + "微服务测试心跳为:正常")
        else:
            # 推送微信提醒
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC(msname + "微服务测试心跳是否正常", "停止")
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
            print(msname + "微测试心跳为:停止")
        # 第一个参数代表多少秒后执行这个action任务
        # 参数priority是优先级，0代表优先级最高,1次之，2次次之…
        s.enter(5, 1, ms_version, (msname,))
        s.run()
        time.sleep(5)
    except:
        print("ms_version执行报错:" + sys.exc_info())
    finally:
        print("===============================微服务监控结束========================================")
    pass


# 测试网站
def ce_yngov():
    try:
        url = Pyconfig.ynwz_url
        http = httplib2.Http()
        s = sched.scheduler(time.time, time.sleep)
        response, content = http.request(url, 'GET')
        # print(content)
        # print(response)
        # print(response.status)
        # return content.decode('unicode-escape').encode('utf-8')
        if (response.status == 200):
            print("网站测试心跳为:正常")
        else:
            # 推送微信提醒
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC("网站测试访问是否正常", "访问异常")
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
            print("网站试心跳为:停止")
        # 第一个参数代表多少秒后执行这个action任务
        # 参数priority是优先级，0代表优先级最高,1次之，2次次之…
        s.enter(5, 1, ce_yngov, ())
        s.run()
        time.sleep(5)
    except:
        print("ms_version执行报错:" + sys.exc_info())
    finally:
        print("===============================监控【网站】结束========================================")
    pass


# 设置定期服务机制
def main_dqzx(h, m, i):
    '''h表示设定的小时，m为设定的分钟'''
    # print("时间为：", h, "|", m)
    # 判断是否达到设定时间，例如0:00
    while True:
        now = datetime.datetime.now()
        # print(now.hour, "|", now.minute, "|", now.second)
        # 到达设定时间，结束内循环
        if now.hour == h and now.minute == m:
            break
        # 不到时间就等20秒之后再次检测
        time.sleep(10)
        # 做正事，一天做一次
    if (i == 'webchat_touser_tx'):
        webchat_touser_tx()
    if (i == 'webchat_to110_tx'):
        webchat_to110_tx()
    if (i == 'crj_tocrjglj_tx'):
        crj_tocrjglj_tx()
    if (i == 'hz_tohzzd_tx'):
        hz_tohzzd_tx()


# 设置定期服务机制
def main_dqzx_tb(h, m, tablename, where, title):
    '''h表示设定的小时，m为设定的分钟'''
    # print("时间为：", h, "|", m)
    # 判断是否达到设定时间，例如0:00
    while True:
        now = datetime.datetime.now()
        # print(now.hour, "|", now.minute, "|", now.second)
        # 到达设定时间，结束内循环
        if now.hour == h and now.minute == m:
            break
        # 不到时间就等20秒之后再次检测
        time.sleep(10)
        # 做正事，一天做一次
    o_i_tx(tablename, where, title)


# 内外网数据监控提醒
def o_i_tx(tablename, where, title):
    try:
        # 互联网链接数据池
        conn_out = DB.conn_out

        # 移动信息网链接数据池
        conn_yd = DB.conn_yd

        # 外网数据库语句
        MainService_o = service.MainService.MainService(conn_out)
        rows1 = MainService_o.selectoialarm(tablename, where)
        # 内网数据库语句
        MainService_i = service.MainService.MainService(conn_yd)
        rows2 = MainService_i.selectoialarm(tablename, where)
        rows1count = rows1[0][0]
        rows1count2 = rows2[0][0]
        if (rows1count > rows1count2):
            cz = rows1count - rows1count2
        else:
            cz = rows1count2 - rows1count
        printstr = "时间 " + str(time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())) + str(
            tablename) + "外网表 " + str(
            rows1count) + "  " + str(
            tablename) + "内网表 " + str(rows1count2) + "  " + "  差值 " + str(cz)
        print(printstr)
        # 推送消息至监控人员--调用运维接口
        if (cz != 0):
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC(str(title) + "内外网数据不匹配", printstr)
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
        print(printline(130))
    except:
        print("o_i_tx执行报错:" + sys.exc_info())
    finally:
        print("===============================监控提醒结束========================================")
    pass


# 微报警外网数据推送给用户监控提醒
def webchat_touser_tx():
    try:
        # 互联网链接数据池
        conn_out = DB.conn_out

        # 外网数据库语句
        MainService_o = service.MainService.MainService(conn_out)
        rows1 = MainService_o.selectiochat()
        rows2 = MainService_o.selectiochat_openid()
        rows1count = rows1[0][0]
        rows2count = rows2[0][0]
        printstr = "时间 " + str(time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())) + " 外网会话数据有 " + str(
            rows1count) + "  条未推送给用户 openid为空的数据有" + str(
            rows2count)
        print(printstr)
        # 推送消息至监控人员--调用运维接口
        if (rows1count > 0):
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC("微报警会话数据推送给用户", printstr)
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
        print(printline(130))
    except:
        print("webchat_touser_tx执行报错:" + sys.exc_info())
    finally:
        print("===============================监控提醒结束========================================")
    pass


# 微报警内网数据推送至110指挥中心监控提醒
def webchat_to110_tx():
    try:
        # 移动信息网链接数据池
        conn_yd = DB.conn_yd

        # 内网数据库语句
        MainService_i = service.MainService.MainService(conn_yd)
        rows2 = MainService_i.selectoialarm_to110()
        rows1count2 = rows2[0][0]
        printstr = "时间 " + str(time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())) + " 微报警内网数据有 " + str(
            rows1count2) + "  条未推送至110指挥中心 "
        print(printstr)
        # 推送消息至监控人员--调用运维接口
        if (rows1count2 > 0):
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC("微报警内网数据至110指挥中心", printstr)
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
        print(printline(130))
    except:
        print("webchat_to110_tx执行报错:" + sys.exc_info())
    finally:
        print("===============================监控提醒结束========================================")
    pass


# 出入境内网数据推送至出入境总队监控提醒
def crj_tocrjglj_tx():
    try:
        # 移动信息网链接数据池
        conn_yd = DB.conn_yd

        # 内网数据库语句
        MainService_i = service.MainService.MainService(conn_yd)
        rows2 = MainService_i.selectoicrjbills_tocrjglj()
        rows1count2 = rows2[0][0]
        printstr = "时间 " + str(time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())) + " 内网数据有 " + str(
            rows1count2) + "  条未推送至出入境管理局 "
        print(printstr)
        # 推送消息至监控人员--调用运维接口
        if (rows1count2 > 0):
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC("出入境内网数据推送至出入境总队", printstr)
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
        print(printline(130))
    except:
        print("crj_tocrjglj_tx执行报错:" + sys.exc_info())
    finally:
        print("===============================监控提醒结束========================================")
    pass


# 户政内网数据推送至户政总队监控提醒
def hz_tohzzd_tx():
    try:
        # 移动信息网链接数据池
        conn_yd = DB.conn_yd

        # 内网数据库语句
        MainService_i = service.MainService.MainService(conn_yd)
        rows2 = MainService_i.selectoihzbills_tohz()
        rows1count2 = rows2[0][0]
        printstr = "时间 " + str(time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())) + " 内网数据有 " + str(
            rows1count2) + "  条户政总队未抓取 "
        print(printstr)
        # 推送消息至监控人员--调用运维接口
        if (rows1count2 > 0):
            # 判断当前的信息是否已经推送过去
            boltrue = sendSmsToOSC("户政内网数据推送至户政", printstr)
            if (boltrue):
                print("推送报警信息到监控人员成功")
            else:
                print("推送报警信息到监控人员失败")
        print(printline(130))
    except:
        print("hz_tohzzd_tx执行报错:" + sys.exc_info())
    finally:
        print("===============================监控提醒结束========================================")
    pass


# 显示分割符的长度
def printline(numcot):
    returnstr = ""
    for index in range(numcot):
        returnstr += "="
    return returnstr


# 欧索企业号微信推送接口调用
def sendSmsToOSC(title, msg):
    url = Pyconfig.ynwx_url
    jsonvar = {"msgtitle": title, "msgcontent": msg, "except_type": "1"}
    # print(jsonvar)
    d = json.dumps(jsonvar)
    headers = {'content-type': 'application/json'}
    print(d)
    req = requests.post(url, data=d, json=json, headers=headers)
    if (req.status_code == 200):
        return True
    else:
        return False
    pass
